package org.example.everyday;

public class Lc2055 {

    public static void main(String[] args) {
        Lc2055 lc2055 = new Lc2055();

        String s = "**|**|***|";
        int[][]  queries = {{2,5},{5,9}};

        int[] result = lc2055.platesBetweenCandles(s,queries);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
    }

        public int[] platesBetweenCandles(String s, int[][] queries) {
            int[] nextCandleIdx = getNextCandleIdx(s);
            int[] preCandleIdx = getPreCandleIdx(s);
            int[] plateCnt = getPlateCnt(s);

            //ans
            int len = queries.length;
            int[] ans = new int[len];
            for(int i = 0; i < len; i++){
                int formerIndex = nextCandleIdx[queries[i][0]];
                int latterIndex = preCandleIdx[queries[i][1]];
                if(formerIndex == -1 || latterIndex == -1 || formerIndex > latterIndex){
                    ans[i] = 0;
                }else{
                    ans[i] = plateCnt[latterIndex] - plateCnt[formerIndex];
                }
            }
            return ans;
        }
        /**
         得到盘子的前缀和
         */
        private int[] getPlateCnt(String s){
            int len = s.length();
            int[] ans = new int[len];

            for(int i = 0; i < len;i++){
                ans[i] += i == 0 ? 0 : ans[i - 1];
                if(s.charAt(i) == '*'){
                    ans[i]++;
                }
            }
            return ans;
        }

        private int[] getNextCandleIdx(String s){
            int len = s.length();
            int[] ans = new int[len];
            int lastIndex = -1;
            for(int i = len - 1; i >= 0; i--){
                if(s.charAt(i) == '|'){
                    lastIndex = i;
                }
                ans[i] = lastIndex;
            }

            return ans;

        }

        private int[] getPreCandleIdx(String s){
            int len = s.length();
            int[] ans = new int[len];
            int lastIndex = -1;
            for(int i = 0; i < len ; i++){
                if(s.charAt(i) == '|'){
                    lastIndex = i;
                }
                ans[i] = lastIndex;
            }

            return ans;

        }


}
